use std::env;
use std::fs;
use std::path::Path;

use anyhow::Result;

// 直接包含 encry_util 文件内容
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/utils/encry_util.rs"));

fn main() -> Result<()> {
    println!("cargo:warning=Build script started");
    println!("cargo:warning=Generating resources...");
    // 仅在release构建且production特性启用时生成加密配置
    if env::var("CARGO_FEATURE_PRODUCTION").is_ok() {//env::var("PROFILE").unwrap() == "release" &&
        println!("cargo:warning=Production release mode detected - generating encrypted config");
        let encrypter = ConfigEncrypter::from_random()?;
        let config_content = fs::read_to_string(".env.production")?;
        let encrypted_config = encrypter.encrypt(&config_content)?;

        let out_dir = env::var("OUT_DIR")?;
        let dest_path = Path::new(&out_dir).join("encrypted_config.rs");

        fs::write(
            dest_path,
            format!(
                "pub const ENCRYPTION_KEY: &str = \"{}\";\n\
                 pub const NONCE: &str = \"{}\";\n\
                 pub const ENCRYPTED_CONFIG: &str = \"{}\";",
                encrypted_config.key,
                encrypted_config.nonce,
                encrypted_config.data
            )
        )?;
    }

    tauri_build::build();
    Ok(())
}